package com.gitee.feizns.quickstart.web.decrypt;

import com.gitee.feizns.dynamic.bean.Props;
import com.gitee.feizns.quickstart.web.resolver.AbstractServletModelAttributeMethodProcessor;
import org.springframework.core.MethodParameter;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;

/**
 * 解密参数解密转换器
 * @see HandlerMethodArgumentResolver
 * @author feizns
 * @since 2023/2/3
 */
public class DecryptServletModelAttributeMethodProcessor extends AbstractServletModelAttributeMethodProcessor {

    /**
     * 解密算法
     */
    private final DecryptionAlgorithm algorithm;
    public DecryptServletModelAttributeMethodProcessor(DecryptionAlgorithm algorithm) {
        this.algorithm = algorithm;
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return super.supportsParameter(parameter)
                && Props.rw(parameter.getParameterType()).anyMatch(prop -> prop.isAnnotationPresent(Decrypt.class));
    }

    @Override
    protected void processTarget(Object target) {
        if ( target != null ) {
            Props.rw(target)
                    .filter(prop -> prop.isAnnotationPresent(Decrypt.class))
                    .forEach(prop -> {
                        String val = prop.val(String.class);
                        if ( val != null )
                            prop.set(algorithm.decrypt(val));
                    });
        }
    }

}
